package com.water_work_form.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.BorderStyle;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.water_work_form.entity.RecordTitration;
import com.water_work_form.mapper.*;
import com.water_work_form.service.RecordTitrationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p>
 * 记录——滴定质控 服务实现类
 * </p>
 *
 * @author xuke
 * @since 2023-10-16
 */
@Service
public class RecordTitrationServiceImpl extends ServiceImpl<RecordTitrationMapper, RecordTitration> implements RecordTitrationService {


    @Autowired
    BasicFormMapper basicFormMapper;

    @Autowired
    BasicSampleMapper basicSampleMapper;

    @Autowired
    BasicPhBlindMapper basicPhBlindMapper;

    @Autowired
    BasicPhMapper basicPhMapper;

    @Autowired
    BasicWaterMapper basicWaterMapper;

    @Autowired
    BasicDrugMapper basicDrugMapper;

    @Autowired
    BasicRestrictionMapper basicRestrictionMapper;

    @Autowired
    BasicFormulaMapper basicFormulaMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;



    /**
     * 记录——分光光度法检测铝、铁、氨、亚硝酸盐原始记录 项目查询（两个查询项+分页+排序）
     * @param checkSite 检测地点（check_site） 若为空则不进行此项查询，否则返回模糊查询后的数据
     * @param checkStartDate 检测日期（check_date） 范围查询开始日期，若为空则不进行此项查询，否则返回check_date大于checkStartDate的数据
     * @param checkEndDate 检测日期（check_date） 范围查询结束日期，若为空则不进行此项查询，否则返回check_date小于checkEndDate的数据
     * @param status 项目状态（status） 若为空则不进行此项查询，否则返回对应数据
     * @param current 分页查询 当前页数
     * @param size 分页查询 每页最大数据量
     * @return 返回符合以上查询条件的数据 并按照 状态（status）、领样日期（receive_date）、检测日期（check_date）的先后顺序作为优先级（即状态status为优先级最高，进行首先排序）进行升序排序
     */
    @Override
    public IPage<RecordTitration> selectRecordTitration(String type, String checkStartDate, String checkEndDate, String checkSite, String status, Integer current, Integer size){
        QueryWrapper<RecordTitration> queryWrapper = new QueryWrapper<>();

        if(type != null && type.length() > 0){
            queryWrapper.eq("type", type);
        }
        if( checkStartDate != null && checkStartDate.length() > 0){
            queryWrapper.ge("check_date", checkStartDate);
        }
        if( checkEndDate != null && checkEndDate.length() > 0){
            queryWrapper.le("check_date", checkEndDate);
        }
        if( checkSite != null && checkSite.length() > 0 ){
            queryWrapper.like("check_site", checkSite);
        }
        if( status != null && status.length() > 0 ){
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByAsc("status", "receive_date", "check_date");
        IPage<RecordTitration> page = new Page<>(current, size);
        return this.page(page,queryWrapper);
    }

    /**
     *
     * @param formName
     * @param sampleName
     * @param phBlindName
     * @param phProject
     * @param waterId
     * @param drugName
     * @param restrictionName
     * @param formulaName
     * @return
     */
    @Override
    public Map<String,Object> selectBasicTitration(String formName, String sampleName, String phBlindName, String phProject,
                                                   String waterId, String drugName, String restrictionName, String formulaName) {
        Map<String,Object> map = new HashMap<>();
        map.put("form", basicFormMapper.getOneByName(formName));
        map.put("sample", basicSampleMapper.getOneByName(sampleName));
        map.put("phBlind", basicPhBlindMapper.getOneByName(phBlindName));
        map.put("ph", basicPhMapper.getOneByName(phProject));
        map.put("water", basicWaterMapper.getOneByName(waterId));
        map.put("drug", basicDrugMapper.listByName(drugName));
        map.put("restriction", basicRestrictionMapper.getOneByName(restrictionName));
        map.put("formula", basicFormulaMapper.getOneByName(formulaName));
        return map;
    }

    /**
     * 记录——分光光度法检测铝、铁、氨、亚硝酸盐原始记录 数据表导出
     * @param recordTitration 需要导出的数据表
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordTitration(RecordTitration recordTitration) throws IOException {

        Map<String, Object> data = new HashMap<String, Object>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        JSONObject form =  JSON.parseObject(recordTitration.getForm());
        JSONObject sample =  JSON.parseObject(recordTitration.getSample());
        JSONObject phBlind =  JSON.parseObject(recordTitration.getPhBlind());
        JSONObject ph =  JSON.parseObject(recordTitration.getPh());
        JSONObject water =  JSON.parseObject(recordTitration.getWater());
        List<String> drug =  Arrays.asList(recordTitration.getDrug());
        JSONObject restriction =  JSON.parseObject(recordTitration.getRestriction());
        JSONObject deviceMessage =  JSON.parseObject(recordTitration.getDeviceMessage());
        JSONObject sampleMessage =  JSON.parseObject(recordTitration.getSampleMessage());
        JSONObject formula =  JSON.parseObject(recordTitration.getFormula());
        JSONObject formulaContent =  JSON.parseObject(formula.get("formulaContent").toString());
        List sampleResult =  JSON.parseArray(recordTitration.getSampleResult());
        Object resultObj = sampleResult.get(sampleResult.size()-1);
        List instrumentNumber = (List) deviceMessage.get("instrumentNumber");
        List certificateNumber = (List) deviceMessage.get("certificateNumber");
        List effectiveDate = (List) deviceMessage.get("effectiveDate");
        String img = "http://localhost:88/file/" + formulaContent.get("url");
        System.out.println(deviceMessage.get("instrumentType"));
        BorderStyle borderStyle = new BorderStyle();
        borderStyle.setType(XWPFTable.XWPFBorderType.NONE); //无边框设置
        if(deviceMessage.get("instrumentType").equals("数显滴定仪")){
            RowRenderData row0 = Rows.create("仪器编号", (String) instrumentNumber.get(0), (String) instrumentNumber.get(1));
            RowRenderData row1 = Rows.create("计量检定证书编号", (String) certificateNumber.get(0), (String) certificateNumber.get(1));
            RowRenderData row2 = Rows.create("证书有效期", (String) effectiveDate.get(0), (String) effectiveDate.get(1));
            Tables.TableBuilder tableBuilder = Tables.of(row0,row1,row2);
            TableRenderData tableRenderData = tableBuilder.border(borderStyle).create();
            data.put("deviceMessageTable",tableRenderData);
            System.out.println(0);
        }else if(deviceMessage.get("instrumentType").equals("滴定管")){
            RowRenderData row3 = Rows.create("规格", (String) deviceMessage.get("specifications"));
            Tables.TableBuilder tableBuilder = Tables.of(row3);
            TableRenderData tableRenderData = tableBuilder.border(borderStyle).create();
            data.put("deviceMessageTable", tableRenderData);
            System.out.println(1);
        }
        data.put("deviceMessage", deviceMessage);
        data.put("receiveDate", dateFormat.format(recordTitration.getReceiveDate()));
        data.put("instrumentType", deviceMessage.get("instrumentType"));
        data.put("checkDate", dateFormat.format(recordTitration.getCheckDate()));
        data.put("form", form);
        data.put("sample", sample);
        data.put("phBlind", phBlind);
        data.put("ph", ph);
        data.put("water", water);
        data.put("drug", drug);
        data.put("restriction", restriction);
        data.put("formulaDescription", formula.get("formulaDescription"));
        data.put("formulaContent", Pictures.ofUrl(img)
                .size(200, 50).create());
        data.put("sampleMessage", sampleMessage);
        data.put("sampleResult", sampleResult.subList(0, sampleResult.size()-1));
        data.put("result", resultObj);
        data.put("list", recordTitration);
        // 插件列表,可以去官网查看，有列循环，还有行循环，这里是行循环实例
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();

        //这里可以指定一个config类，用来指定一些规则，也可以改变模板中{{}}的这种格式
        Configure config = Configure.builder()
                .bind("sampleResult", policy)
                .bind("drug", policy).build();

        //渲染文件
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordTitration.docx",config);
        compile.render(data);
        //输出为文件，指定输出文件名
        compile.writeToFile(destFilePath + recordTitration.getId() + "out_recordTitration.docx");
        compile.close();
    }

}
